package dataStructure.graph;

/**
 * 多源最短路径算法
 */
public class Floyd {
    private static int INF = Integer.MAX_VALUE;

    public static void floyd(GraphMatrix graph) {
        int vertexNum = graph.getVertexNum();
        int[][] distance = new int[vertexNum][vertexNum];

        // 初始化距离矩阵
        for (int i = 0; i < vertexNum; i++) {
            for (int j = 0; j < vertexNum; j++) {
                distance[i][j] = graph.edges[i][j];
                if (i != j && distance[i][j] == 0) {
                    distance[i][j] = INF;
                }
            }
        }
        System.out.println("距离矩阵：");
        showDistance(distance, vertexNum);

        //循环更新矩阵的值
        for (int k = 0; k < vertexNum; k++) {
            for (int i = 0; i < vertexNum; i++) {
                for (int j = 0; j < vertexNum; j++) {
                    //以k为中间点，如果i->k->j的总距离小于当前i->j的距离，更新距离矩阵
                    int temp = (distance[i][k] == INF || distance[k][j] == INF) ?
                            INF : distance[i][k] + distance[k][j];
                    if (distance[i][j] > temp) {
                        distance[i][j] = temp;
                    }
                }
            }
            System.out.println("count" + k);
            showDistance(distance, vertexNum);
        }

        // 打印floyd最短路径的结果
        System.out.println("Floyd最短路径的结果:");
        showDistance(distance, vertexNum);
    }

    private static void showDistance(int[][] distance, int vertexNum) {
        for (int i = 0; i < vertexNum; i++) {
            for (int j = 0; j < vertexNum; j++) {
                if (distance[i][j] == INF) {
                    System.out.printf("%4s ", "INF");
                } else {
                    System.out.printf("%4d ", distance[i][j]);
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        GraphMatrix<String> graph = new GraphMatrix<>("ABCD");
        graph.type = GraphMatrix.GraphType.DIRECTED_GRAPH;
        graph.addEdge("A", "B", 1);
        graph.addEdge("A", "C", 2);
        graph.addEdge("A", "D", 3);
        graph.addEdge("B", "A", 4);
        graph.addEdge("C", "B", 5);
        graph.addEdge("C", "D", 1);
        graph.addEdge("D", "B", 1);
        graph.addEdge("D", "C", 2);
        graph.information();
        floyd(graph);
    }
}
